<!--
 * @description: 综合安全管理 首页
 * @author: cuicui
 * @Date: 2023-11-23 11:53:14
 * @LastEditTime: 2023-11-27 23:43:02
 * @LastEditors: cuicui
-->
<template>
  <business-layout title='实时数据' custom-title>
    <template slot='header'>
      <div class='table-tab'>
        <a-tabs :default-active-key='0' v-model='activeKey' @edit='handleEditTab'>
          <a-tab-pane :tab='item' v-for='(item, index) in tabs' :key='index'>
          </a-tab-pane>
        </a-tabs>
      </div>

      <div class='table-page-search-wrapper' slot='query'>
        <a-row style='height: 40px;'>
          <a-form style='height: 40px;' :form='form' layout='inline' @submit='handleQueryData'>
            <a-col :span='24' style='height: 40px;'>
              <a-form-item>
                <a-date-picker
                  v-model='queryParam.startTime'
                  valueFormat='YYYY-MM-DD 00:00:00'
                  format='YYYY-MM-DD 00:00:00'
                  placeholder='请选择开始时间'
                  :disabled-date='startDisabledDate'
                />
                <a-date-picker
                  style='margin-left: 10px'
                  v-model='queryParam.endTime'
                  :disabled-date='endDisabledDate'
                  format='YYYY-MM-DD 23:59:59'
                  valueFormat='YYYY-MM-DD 23:59:59'
                  placeholder='请选择结束时间'
                />
                <a-button type='primary' html-type='submit' style='margin-left: 10px;' >
                  <a-icon type='search' />
                  查询
                </a-button>
                <a-button html-type='reset' style='margin-left: 10px;' @click='handleResetData'>
                  重置
                </a-button>
              </a-form-item>
            </a-col>
          </a-form>
        </a-row>
      </div>

      <template slot='btns'>
      </template>
    </template>

    <s-table
      ref='table'
      size='default'
      rowKey='id'
      :columns='computedTableColuns'
      :data='loadData'
      :showPagination='false'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='alarmMessage' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>
      <span slot='abnormalTime' slot-scope='text'>
        <span>{{ text| dayjs }}</span>
      </span>
      <span slot='estimateTime' slot-scope='text'>
        <span>{{ text| dayjs }}</span>
      </span>
      <span slot='abnormalTime' slot-scope='text'>
        <span>{{ text| dayjs }}</span>
      </span>
      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleEdit(record)'>详情</a>
        </template>
      </span>
    </s-table>


    <!--    <create-point-->
    <!--      ref='createHistoryModal'-->
    <!--      :visible='historyVisible'-->
    <!--      :loading='confirmLoading'-->
    <!--      :model='{}'-->
    <!--      @cancel='historyVisible = false'-->
    <!--      @ok='handleHistoryOk'-->
    <!--    />-->
    <!--    <details :loading='loading' :visible='visible' :deviceId='deviceId' :groupId='groupId'></details>-->
    <data-detail
      ref='dialog'
      :visible='visible'
      :DatadeviceId='DatadeviceId'
      :loading='confirmLoading'
      :activeKey='activeKey'
      :model='mdl'
      @ok='handleOk'
      @cancel='handleCancel'
    />
    <dataDetailMore
      ref='dataDetailMore'
      :visible='datavisible'
      :DatagroupId='DatadeviceId'
      :loading='confirmLoading'
      :model='mdl'
      @ok='handleOk'
      @cancel='handleCancel'
    />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'

import {
  getAllReliablilityDevice,
  singleDeviceAbnormalGraphData,
  singleDeviceAbnormalStatistics,
  multiDeviceAbnormalGraphData,
  multiDeviceAbnormalStatistics
} from '@/api/customReport'
import CreatePoint from '@/business-components/create-point'
import Details from './details.vue'
import CreateTab from '@/business-components/create-tab'
import dataDetailMore from '@/views/security/physics/dataDetailMore.vue'
import dataDetail from '@/views/security/physics/dataDetail.vue'
import CreateView from '@/business-components/create-view/index.vue'

const singleColumns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '设备名称',
    dataIndex: 'deviceName'
  },
  {
    title: '数据名',
    dataIndex: 'dataName'
  },
  {
    title: '异常频率',
    dataIndex: 'abnormalFrequency'
  },
  {
    title: '异常时间',
    dataIndex: 'abnormalTime',
    scopedSlots: { customRender: 'abnormalTime' }
  },
  {
    title: '报警信息',
    dataIndex: 'alarmMessage',
    scopedSlots: { customRender: 'alarmMessage' }
  },
  {
    title: '数据值',
    dataIndex: 'dataValue'
  },
  {
    title: '设备ID',
    dataIndex: 'deviceId'
  },
  {
    title: '持续时间',
    dataIndex: 'durTime'
  },
  {
    title: '预计时间',
    dataIndex: 'estimateTime',
    scopedSlots: { customRender: 'estimateTime' }
  },
  {
    title: '正常范围',
    dataIndex: 'normalRange'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

const singleCountColumns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '设备名称',
    dataIndex: 'deviceName'
  },
  {
    title: '设备ID',
    dataIndex: 'deviceId'
  },
  {
    title: '异常频率',
    dataIndex: 'count'
  }
]

const multiColumns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '数据组名称',
    dataIndex: 'groupName'
  },
  {
    title: '数据组ID',
    dataIndex: 'groupId'
  },
  {
    title: '持续时间',
    dataIndex: 'durTime'
  },
  {
    title: '异常值',
    dataIndex: 'abnormalValue'
  },
  {
    title: '异常时间',
    dataIndex: 'abnormalTime',
    scopedSlots: { customRender: 'abnormalTime' }
  },
  {
    title: '预计时间',
    dataIndex: 'estimateTime',
    scopedSlots: { customRender: 'estimateTime' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

const multiCountColumns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '数据组名称',
    dataIndex: 'groupName'
  },
  {
    title: '数据组ID',
    dataIndex: 'groupId'
  },
  {
    title: '异常频率',
    dataIndex: 'count'
  }
]


export default {
  name: 'TableList',
  components: {
    CreateView,
    CreateTab,
    STable,
    Ellipsis,
    CreatePoint,
    Details,
    dataDetail,
    dataDetailMore
  },
  data() {
    return {
      deviceId: '',
      groupId: '',
      form: this.$form.createForm(this),
      historyVisible: false,
      tabs: ['单数据异常检测明细', '单数据异常检测统计', '多数据关联检测明细', '多数据关联检测统计'],
      activeKey: 0,
      DatadeviceId: '',
      // create model
      visible: false,
      datavisible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      slectOption: [],
      dataFunList: [singleDeviceAbnormalGraphData, singleDeviceAbnormalStatistics, multiDeviceAbnormalGraphData, multiDeviceAbnormalStatistics],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return this.dataFunList[this.activeKey](requestParameters).then(res => {
          return {
            endRow: 10,
            hasNextPage: false,
            hasPreviousPage: false,
            isFirstPage: false,
            isLastPage: false,
            list: [1, 3].includes(this.activeKey) ? res : (res.dataItems || []),
            navigateFirstPage: 0,
            navigateLastPage: 0,
            navigatePages: 0,
            navigatepageNums: null,
            nextPage: 0,
            pageNum: 1,
            pageSize: 10,
            pages: 3,
            prePage: 0,
            size: 10,
            startRow: 0,
            total: 1
          }
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {},

  computed: {
    computedTableColuns() {
      if (this.activeKey === 0) {
        return singleColumns
      } else if (this.activeKey === 1) {
        return singleCountColumns
      } else if (this.activeKey === 2) {
        return multiColumns
      } else if (this.activeKey === 3) {
        return multiCountColumns
      }
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  watch: {
    activeKey(val) {
      this.activeKey = val
      this.$nextTick(() => {
        this.$refs.table.refresh()
      })
    }
  },
  mounted() {
    this.getAllReliablilityDevice()
  },
  methods: {
    startDisabledDate(startValue) {
      const endValue = this.queryParam.endTime
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > moment(endValue).valueOf()
    },
    endDisabledDate(endValue) {
      const startValue = this.queryParam.startTime
      if (!startValue || !endValue) {
        return false
      }
      return moment(startValue).valueOf() >= endValue.valueOf()
    },
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.$refs.table.refresh()
    },
    handleQueryData(e) {
      e.preventDefault()
      this.$refs.table.refresh()
    },
    getAllReliablilityDevice() {
      getAllReliablilityDevice().then(res => {
        this.slectOption = res.map(item => {
          return {
            ...item,
            key: item.deviceId,
            label: item.deviceName
          }
        })
        this.form.setFieldsValue({
          deviceId: this.slectOption[0].key
        })
      })
    },
    handleEditTab(tagetKey, action) {
      if (action === 'add') {
        this.historyVisible = true
      }
    },
    handleHistoryOk() {
      const form = this.$refs.createHistoryModal.form
      const value = form.getFieldsValue()
      this.tabs.push(value.pageName)
      this.historyVisible = false
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      if (this.activeKey === 0) {
        this.visible = true
        this.DatadeviceId = record.deviceId
      } else if (this.activeKey === 2) {
        this.datavisible = true
        this.DatadeviceId = record.groupId
      }
    },
    handleOk() {
      if (this.activeKey === 0) {
        this.visible = false
      } else {
        this.datavisible = false
      }
    },
    // handleOk() {
    //   const form = this.$refs.createModal.form
    //   this.confirmLoading = true
    //   form.validateFields((errors, values) => {
    //     if (!errors) {
    //       console.log('values', values)
    //       if (values.id > 0) {
    //         // 修改 e.g.
    //         new Promise((resolve, reject) => {
    //           setTimeout(() => {
    //             resolve()
    //           }, 1000)
    //         }).then(res => {
    //           this.visible = false
    //           this.confirmLoading = false
    //           // 重置表单数据
    //           form.resetFields()
    //           // 刷新表格
    //           this.$refs.table.refresh()
    //
    //           this.$message.success('更新成功')
    //         })
    //       } else {
    //         // 新增
    //         new Promise((resolve, reject) => {
    //           setTimeout(() => {
    //             resolve()
    //           }, 1000)
    //         }).then(res => {
    //           this.visible = false
    //           this.confirmLoading = false
    //           // 重置表单数据
    //           form.resetFields()
    //           // 刷新表格
    //           this.$refs.table.refresh()
    //
    //           this.$message.success('新增成功')
    //         })
    //       }
    //     } else {
    //       this.confirmLoading = false
    //     }
    //   })
    // },
    handleCancel() {
      if (this.activeKey === 0) {
        this.visible = false
      } else {
        this.datavisible = false
      }
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}
</style>
